package cos

import (
	"context"
	"encoding/json"
	"fmt"
	"time"

	"github.com/go-resty/resty/v2"
)

type GetCredentialReq struct {
	BucketPrefix string `json:"bucket_prefix"` // bucket 前缀
}

type GetCredentialRes struct {
	TmpSecretId string `json:"tmp_secret_id"`
	// 临时密钥的 TmpSecretKey
	TmpSecretKey string `json:"tmp_secret_key"`
	// 临时密钥的 sessionToken
	SessionToken string `json:"session_token"`
	// 临时密钥失效时间戳，是申请临时密钥时，时间戳加 durationSeconds
	ExpiredTime uint64 `json:"expired_time"`
	// 开始时间
	StartTime   int    `json:"start_time"`
	// 桶
	Bucket string `json:"bucket"`
	// 地区
	Region string `json:"region"`
}

func (s *CosClient) GetCredential(ctx context.Context, req *GetCredentialReq) (res *GetCredentialRes, err error) {
	bytes, err := json.Marshal(req)
	if err != nil {
		return
	}
	url := fmt.Sprintf("%s/sts/credential", s.endpoint)
	result := &cosInvokeRes[GetCredentialRes]{}
	errRes := &cosErrorRes{}
	fmt.Println("start==>", time.Now())
	client := resty.New()
	_, err = client.R().
		SetContext(ctx).
		SetHeader("Content-Type", "application/json").
		SetBody(string(bytes)).
		SetResult(result).
		SetError(errRes).
		Post(url)
	fmt.Println("end==>", time.Now())
	if err != nil {
		return
	}
	if result.StatusText != "ok" {
		err = fmt.Errorf("GetCredential Err:%s", errRes.ErrorText)
		return
	}
	res = result.Data
	
	return
}
